import { ref, watch, nextTick, computed, onMounted, reactive } from 'vue'
// import {useAccountStore} from '@/store/account'
import { useTagsViewStore } from '@/store/tagsView'
import { useAppStore } from '@/store/app'

import { useRoute, useRouter } from 'vue-router'
import _ from 'lodash'

export default function useTagsView(proxy, config) {
  onMounted(() => {
    console.log('tagsView hook mounted!')
  })

  // const accountStore = useAccountStore()

  // 静态路由 + 动态路由
  // const routes = accountStore.routes
  const tagsViewStore = useTagsViewStore()

  const appStore = useAppStore()

  function initTags() {
    // 添加affixTags
    // console.log(router)
    router.getRoutes().forEach((route) => {
      if (route?.meta?.affix === true) {
        tagsViewStore.addView(route)
      }
    })
  }

  const route = useRoute()
  watch(route, () => {
    addTags()
    moveToCurrentTag()
  })

  const activeTag = computed(() => {
    const { path } = route
    return path
  })

  function isActiveTag(tag) {
    return tag.path === activeTag.value
  }

  function addTags() {
    // console.log(route, 'addTags')
    const { name } = route
    // 重定向没有name,所以不会额外添加重定向tags
    if (name) {
      tagsViewStore.addView(route)
    }
  }

  function closeTags(tag) {
    const deleteIndex = tagsViewStore.deleteView(tag)
    if (isActiveTag(tag)) {
      toLastView(deleteIndex, tag)
    }
  }

  const router = useRouter()

  // const visitedViews = tagsViewStore.visitedViews

  function toLastView(deleteIndex, view) {
    const latestIndex = deleteIndex < 0 ? 0 : deleteIndex - 1
    const latestView = tagsViewStore.visitedViews[latestIndex]
    if (latestView) {
      // console.log(latestView.fullPath, 'latestView')
      router.push(latestView.fullPath)
    } else {
      // now the default is to redirect to the home page if there is no tags-view,
      // you can adjust it according to your needs.
      if (view.name === 'Dashboard') {
        // to reload home page
        router.replace({ path: '/redirect' + view.fullPath })
      } else {
        router.push('/')
      }
    }
  }

  function moveToCurrentTag() {
    // console.log(visitedViews, 'moveToCurrentTag')
    nextTick(() => {
      for (const view of tagsViewStore.visitedViews) {
        // 命名路由name不会重复
        if (view.name === route.name) {
          // console.log(proxy.$refs[config.scrollPaneRef])
          // 解决异常 Cannot read properties of undefined (reading 'path') => moveToTarget()内在path前加?解决
          proxy.$refs[config.scrollPaneRef].moveToTarget(view)
          // 包含请求参数的全路径
          // if (view.fullPath !== route.fullPath) {
          //   console.log('update view')
          // }
        }
      }
    })
  }

  const contextMenu = reactive({
    visible: false,
    currentTag: {},
    top: 0,
    left: 0
  })

  watch(
    () => contextMenu.visible,
    (val) => {
      if (val) {
        document.body.addEventListener('click', closeContextMenu)
      } else {
        document.body.removeEventListener('click', closeContextMenu)
      }
    }
  )

  function openContextMenu(tag, e) {
    // console.log(proxy.$el, 'openContextMenu')

    // TODO proxy.$el.offsetWidth undefined, 后期排查原因
    const offset = (appStore.sidebarOpen ? -200 : -54) + 15
    contextMenu.currentTag = tag
    contextMenu.left = e.clientX + offset
    contextMenu.top = e.clientY
    contextMenu.visible = true
  }

  function closeContextMenu() {
    contextMenu.visible = false
  }

  function isAffixTag(tag) {
    return tag?.meta.affix === true
  }

  function refreshSelectedTag() {
    const route = contextMenu.currentTag
    tagsViewStore.deleteCachedViews(route)
    // console.log(tagsViewStore.cachedViews)
    const { path, query } = route
    router.replace({
      path: '/redirect' + path,
      query: query
    })
  }

  function closeSelectedTag() {
    // console.log(contextMenu.currentTag, 'closeSelectedTag')
    closeTags(contextMenu.currentTag)
  }

  function closeOthersTags() {
    tagsViewStore.deleteOthersViews(contextMenu.currentTag)
  }

  function closeLeftTags() {
    tagsViewStore.deleteLeftViews(contextMenu.currentTag)
  }

  function closeRightTags() {
    tagsViewStore.deleteRightViews(contextMenu.currentTag)
  }

  function closeAllTags() {
    tagsViewStore.deleteAllViews()
  }

  function isFirstView() {
    return (
      tagsViewStore.firstViews &&
      tagsViewStore.firstViews.fullPath === contextMenu.currentTag.fullPath
    )
  }

  function isLastView() {
    return (
      tagsViewStore.lastViews &&
      tagsViewStore.lastViews.fullPath === contextMenu.currentTag.fullPath
    )
  }

  return {
    activeTag,
    contextMenu,
    isActiveTag,
    initTags,
    addTags,
    moveToCurrentTag,
    closeTags,
    toLastView,
    openContextMenu,
    isAffixTag,
    refreshSelectedTag,
    closeSelectedTag,
    closeOthersTags,
    closeLeftTags,
    closeRightTags,
    closeAllTags,
    isFirstView,
    isLastView
  }
}
